<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import gnzjService from '@/api/gnzj'
import pinyin from 'pinyin-match'
import { useMainStore } from '@/store/main'
const userInfo = useMainStore().userInfo
const plainOptions = ['省级院', '市级院', '基层院']
const columns = [
  {
    title: '发布单位',
    dataIndex: 'dwmc',
  },
  {
    title: '功能名称',
    dataIndex: 'gnmc',
  },
  {
    title: '功能显示名称',
    dataIndex: 'gnxsmc',
  },
  {
    title: '功能地址',
    dataIndex: 'gndz',
  },
  {
    title: '功能编辑名称',
    dataIndex: 'qxbjqmc',
  },
  {
    title: '功能编辑器地址',
    dataIndex: 'qxbjqdz',
  },
  {
    title: '是否快捷方式',
    dataIndex: 'sfkjfs',
  },
]
const pagination = ref({
  pageSize: 10, // 一页的数据限制
  current: 1, // 当前页
  total: 0, // 总数
  pageChange: (val: { pageSize?: number; pageIndex?: number }) => {
    // 改变 pageSize时的回调
    pagination.value.current = val.pageIndex || pagination.value.current
    pagination.value.pageSize = val.pageSize || pagination.value.pageSize
    getTableLists()
  },
})
const replaceFields = {
  children: 'children',
  label: 'mc',
}
const gData = ref<any[]>([]) //树形数据
const gData1 = ref<any[]>([])
const selectTreeNode = ref('')
const nodeMessege = ref<{ [key: string]: any }>({}) //节点信息
const tableLists = ref([]) //table数据
const form = ref({
  flbm: '',
  fflbm: '',
  flmc: '',
  flxh: '',
  fltb: undefined,
})
const tjflForm = ref({
  fflbm: '',
  flmc: '',
  flxh: '',
  fltb: undefined,
})
const gndy = ref({
  gnmc: '',
  gnxsmc: '',
  gndz: '',
  dwmc: '',
  gncs: '',
  qxbjqmc: '',
  qxbjqdz: '',
  sfkjfs: '',
  flbm: '',
  bz: '',
  gnxh: '',
  syfw: ['省级院'],
  gnlb: '',
  sfcdxs: 'Y',
  gntb: '',
  gnlb_dm: undefined,
  sfdsfgn: undefined,
})
const gnflLists = ref([])
const flag = ref(true)
const tjfLFlag = ref(false)
const expandedKeys = ref<string[]>([])
const gnlbLists = ref([])
const loading = ref(false)
const getGnlbLists = async () => {
  const res = await gnzjService.queryTable({ lbbm: '0035' })
  gnlbLists.value = res.data
}
// 一级节点得删除
const node1shanChu = () => {
  if (!nodeMessege.value.isSave) {
    return
  }
  const data = {
    flbm: nodeMessege.value?.bm,
    zhxgrbm: userInfo.rybm,
  }
  gnzjService.deleteGnfl(data).then(() => {
    ElMessage.success('操作成功')
    serchMenuLeft()
    getSelectLists()
  })
}
const isSaveBtn = () => {
  if (!nodeMessege.value?.isSave) {
    return
  }
  const data = {
    ...form.value,
    dwbm: userInfo.dwbm,
    dwmc: userInfo.dwmc,
    zhxgrbm: userInfo.rybm,
  }
  gnzjService.updateGnfl(data).then(() => {
    ElMessage.success('操作成功')
    serchMenuLeft()
    getSelectLists()
  })
}
// 添加分类
const tjfl = () => {
  tjfLFlag.value = true
}

// 添加分类保存
const tjflBaoCun = async () => {
  if (tjflForm.value.flxh !== '' && tjflForm.value.flmc !== '') {
    const data = {
      bz: '',
      cjrbm: userInfo.rybm,
      cjrmc: userInfo.mc,
      dwbm: userInfo.dwbm,
      dwmc: userInfo.dwmc,
      fflbm: tjflForm.value.fflbm,
      flmc: tjflForm.value.flmc,
      fltb: '',
      flxh: tjflForm.value.flxh,
    }
    await gnzjService.addGnfp(data)
    ElMessage.success('新增成功')
    serchMenuLeft()
    getSelectLists()
  } else {
    ElMessage.warning('完善信息')
  }
}
//获取功能分类最大序号
const getMaxNum = () => {
  gnzjService.getMaxXh({ dwbm: userInfo.dwbm }).then((res: any) => {
    gndy.value.gnxh = res.data.flxh
  })
}
// 获取功能分类下拉列表
const getSelectLists = () => {
  gnzjService.getSelects({ dwbm: userInfo.dwbm }).then((res) => {
    gnflLists.value = res.data
  })
}
// 添加功能
const addGn = () => {
  gndy.value.dwmc = userInfo.dwmc
  getMaxNum()
  gndy.value.flbm = nodeMessege.value?.bm
  flag.value = false
}
// 保存
const preservation = () => {
  if (
    gndy.value.gnmc !== '' &&
    gndy.value.gnxsmc !== '' &&
    gndy.value.gnxh !== '' &&
    gndy.value.gndz !== '' &&
    gndy.value.sfcdxs !== '' &&
    gndy.value.syfw.length > 0
  ) {
    switch (nodeMessege.value.level) {
      case '1':
        baoCun()
        break
      case '2':
        xiuGai()
        break
    }
  } else {
    ElMessage.warning('请完善信息')
  }
}
// 保存
const baoCun = async () => {
  await gnzjService.addGnDy({
    ...gndy.value,
    dwbm: userInfo.dwbm,
    cjrbm: userInfo.rybm,
    cjrmc: userInfo.mc,
  })
  serchMenuLeft()
  getSelectLists()
  ElMessage.success('操作成功')
}
// 修改信息
const xiuGai = async () => {
  await gnzjService.changeGndy({
    ...gndy.value,
    dwbm: userInfo.dwbm,
    zhxgrbm: userInfo.rybm,
    zhxgrmc: userInfo.mc,
  })
  serchMenuLeft()
  getSelectLists()
  ElMessage.success('修改成功')
}
// 删除
const delet = async () => {
  if (nodeMessege.value.level === 1) return
  const data = {
    dwbm: userInfo.dwbm,
    gnbm: nodeMessege.value?.bm,
    zhxgrbm: userInfo.rybm,
    zhxgrmc: userInfo.mc,
  }
  await gnzjService.deleteGndy(data)
  serchMenuLeft()
  getSelectLists()
  ElMessage.success('删除成功')
}
const serchMenuLeft = () => {
  gnzjService.queryTree({ dwbm: userInfo.dwbm }).then((res) => {
    flag.value = true
    gData.value = res.data
    gData1.value = JSON.parse(JSON.stringify(res.data)) //用于筛选
    selectTreeNode.value = res.data[0].bm
    nodeMessege.value = res.data[0] //节点信息
    getTableLists() //查询表格
    getTop()
    tjfLFlag.value = false
  })
}
const handClick = (data: any) => {
  gndy.value = {
    gnmc: '',
    gnxsmc: '',
    gndz: '',
    dwmc: '',
    gncs: '',
    qxbjqmc: '',
    qxbjqdz: '',
    sfkjfs: '',
    flbm: '',
    bz: '',
    gnxh: '',
    syfw: ['省级院'],
    gnlb: '',
    sfcdxs: 'Y',
    gntb: '',
    gnlb_dm: undefined,
    sfdsfgn: undefined,
  }
  tjfLFlag.value = false
  nodeMessege.value = data
  selectTreeNode.value = data.bm
  //不同的节点部分页面的显示隐藏
  if (nodeMessege.value.level === 1) {
    flag.value = true
  }
  if (nodeMessege.value.level === 2) {
    flag.value = false
    getGndyMsg()
    return
  }
  getTableLists() //查询表格
  getTop()
}
// 单个查询
const getGndyMsg = async () => {
  const data = {
    dwbm: userInfo.dwbm,
    gnbm: nodeMessege.value?.bm,
  }
  const res = await gnzjService.getGnDy(data)
  gndy.value = res as unknown as any
}
const getTop = () => {
  const data = {
    dwbm: userInfo.dwbm,
    flbm: nodeMessege.value?.bm,
  }
  gnzjService.getGnfl(data).then((res) => {
    form.value = res.data || form.value
  })
}
const getTableLists = () => {
  loading.value = true
  const data = {
    filter: {
      dwbm: userInfo.dwbm,
      flbm: nodeMessege.value?.bm,
    },
    orderBy: '',
    pageNum: pagination.value.current,
    pageSize: pagination.value.pageSize,
  }
  gnzjService.getGnTable(data).then((res: any) => {
    loading.value = false
    tableLists.value = res.data.list
    pagination.value.total = res.data.total
  })
}
const gnFilter = ref('')
const onChange = (value: string) => {
  if (value) {
    const tree = JSON.parse(JSON.stringify(gData1.value))
    gData.value = filter(tree, value)
  } else {
    gData.value = gData1.value
  }
}
// nodes就是树形的最原始数据，query就是关键字，最后会返回满足条件的节点数组
const filter = (nodes: any[], query: string) => {
  // 条件就是节点的title过滤关键字
  const predicate = (node: any) => pinyin.match(node.mc, query)
  if (!(nodes && nodes.length)) {
    return []
  }
  const newChildren = []
  for (const node of nodes) {
    // 以下两个条件任何一个成立，当前节点都应该加入到新子节点集中
    // 1. 子孙节点中存在符合条件的，即 subs 数组中有值
    // 2. 自己本身符合条件
    const subs = filter(node.children, query)
    if (predicate(node)) {
      newChildren.push(node)
    } else if (subs && subs.length) {
      node.children = subs
      newChildren.push(node)
      expandedKeys.value = [node.bm]
    }
  }

  return newChildren.length ? newChildren : []
}
serchMenuLeft()
getSelectLists()
getGnlbLists()
const filterFn = (value: string, data: any, node: any) => {
  if (value) return pinyin.match(node.label, value)
  return true
}
</script>

<template>
  <div class="gnzj-permission" v-loading="loading">
    <div class="gnzj-left" style="position: relative">
      <div class="tab-box">
        <div class="bottom" style="margin-top: 20px; height: calc(100% - 52px); padding: 0 10px">
          <el-input
            v-model="gnFilter"
            suffix-icon="Search"
            style="margin-bottom: 8px"
            @input="onChange"
            clearable
          />
          <el-scrollbar max-height="calc(100vh - 420px)">
            <el-tree
              style="width: 100%"
              @node-click="handClick"
              :current-node-key="selectTreeNode"
              :default-expanded-keys="expandedKeys"
              :data="gData"
              :props="replaceFields"
              check-on-click-node
              :expand-on-click-node="false"
              node-key="bm"
            >
              <template #default="{ node, data }">
                <el-icon>
                  <Folder v-if="data.level === '1'" />
                  <Document v-else-if="data.level === '2'" />
                </el-icon>
                <span style="margin-left: 4px">{{ node.label }}</span>
              </template>
            </el-tree>
          </el-scrollbar>
        </div>
        <div
          class="btn-group-item"
          style="position: absolute; right: 5px; bottom: 5px"
          @click="tjfl"
        >
          <el-button link icon="Plus">添加分类</el-button>
        </div>
      </div>
    </div>

    <!-- 点击一级节点 -->
    <div class="right" v-if="flag && !tjfLFlag">
      <div class="tab-box" style="padding: 10px">
        <div style="height: 50px; line-height: 50px">
          <div style="float: right">
            <el-button
              v-if="nodeMessege?.isSave"
              link
              type="primary"
              icon="DocumentAdd"
              @click="isSaveBtn"
            >
              保存
            </el-button>
            <el-button link type="primary" icon="Plus" @click="addGn"> 添加功能 </el-button>
            <el-button
              v-if="nodeMessege?.isSave"
              link
              type="primary"
              icon="Delete"
              @click="node1shanChu"
            >
              删除
            </el-button>
          </div>
        </div>
        <div style="height: 80px">
          <table class="riginalTable" style="table-layout: fixed" aria-describedby="分类">
            <tr>
              <th>上级分类</th>
              <th style="padding-right: 0">
                <el-tree-select
                  style="width: 100%"
                  :disabled="true"
                  v-model="form.fflbm"
                  :props="replaceFields"
                  :data="gnflLists"
                  node-key="bm"
                  clearable
                  check-strictly
                  :filter-node-method="filterFn"
                  filterable
                  defaultExpandAll
                />
              </th>
              <th>分类名称</th>
              <th>
                <input
                  :style="{ cursor: nodeMessege?.isSave ? '' : 'not-allowed' }"
                  class="riginalInput"
                  v-model="form.flmc"
                  :disabled="!nodeMessege?.isSave"
                />
              </th>
            </tr>
            <tr>
              <td>序号</td>
              <td>
                <input
                  :style="{ cursor: nodeMessege?.isSave ? '' : 'not-allowed' }"
                  class="riginalInput"
                  v-model="form.flxh"
                  :disabled="!nodeMessege?.isSave"
                />
              </td>
              <td>分类图标</td>
              <td>
                <input
                  :style="{ cursor: nodeMessege?.isSave ? '' : 'not-allowed' }"
                  class="riginalInput"
                  v-model="form.fltb"
                  :disabled="!nodeMessege?.isSave"
                />
              </td>
            </tr>
          </table>
        </div>
        <div style="margin-top: 10px; height: calc(100% - 190px)">
          <el-table :data="tableLists">
            <el-table-column
              v-for="column in columns"
              show-overflow-tooltip
              :key="column.dataIndex"
              :prop="column.dataIndex"
              :label="column.title"
            />
          </el-table>
          <div style="margin-top: 12px">
            <RePager
              :page-change="pagination.pageChange"
              :total="pagination.total"
              :page-size="pagination.pageSize"
              :current="pagination.current"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 点击二级节点 -->
    <div class="right" v-if="!flag && !tjfLFlag">
      <div class="tab-box" style="padding: 10px">
        <div style="height: 50px; line-height: 50px">
          <div style="float: right">
            <el-button link type="primary" icon="DocumentAdd" @click="preservation">
              保存
            </el-button>
            <el-button
              v-if="!flag && nodeMessege.level == '2'"
              link
              type="danger"
              icon="Delete"
              @click="delet"
            >
              删除
            </el-button>
          </div>
        </div>
        <div style="height: 300px">
          <table class="riginalTable" style="table-layout: fixed" aria-describedby="分类">
            <tr>
              <th>
                功能名称
                <span class="red">*</span>
              </th>
              <th>
                <input class="riginalInput" v-model="gndy.gnmc" />
              </th>
              <th>
                功能显示名称
                <span class="red">*</span>
              </th>
              <th>
                <input class="riginalInput" v-model="gndy.gnxsmc" />
              </th>
            </tr>
            <tr>
              <td>
                功能地址
                <span class="red">*</span>
              </td>
              <td>
                <input class="riginalInput" v-model="gndy.gndz" />
              </td>
              <td>功能图标</td>
              <td>
                <input class="riginalInput" v-model="gndy.gntb" />
              </td>
            </tr>
            <tr>
              <td>发布单位</td>
              <td>
                <input
                  style="width: 100%; cursor: not-allowed"
                  class="riginalInput"
                  v-model="gndy.dwmc"
                  disabled
                />
              </td>
              <td>功能初始参数</td>
              <td>
                <input class="riginalInput" v-model="gndy.gncs" />
              </td>
            </tr>
            <tr>
              <td>功能编辑器名称</td>
              <td>
                <input class="riginalInput" v-model="gndy.qxbjqmc" />
              </td>
              <td>功能编辑器地址</td>
              <td>
                <input class="riginalInput" v-model="gndy.qxbjqdz" />
              </td>
            </tr>
            <tr>
              <td>是否快捷方式</td>
              <td style="text-align: left">
                <el-radio-group v-model="gndy.sfkjfs">
                  <el-radio label="Y"> 是 </el-radio>
                  <el-radio label="N"> 否 </el-radio>
                </el-radio-group>
              </td>
              <td>功能分类</td>
              <td style="width: 100%; padding-right: 0">
                <el-tree-select
                  style="width: 100%"
                  v-model="gndy.flbm"
                  :props="replaceFields"
                  :data="gnflLists"
                  node-key="bm"
                  clearable
                  check-strictly
                  :filter-node-method="filterFn"
                  filterable
                  defaultExpandAll
                />
              </td>
            </tr>
            <tr>
              <td>是否第三方功能</td>
              <td style="text-align: left">
                <el-radio-group v-model="gndy.sfdsfgn">
                  <el-radio label="Y"> 是 </el-radio>
                  <el-radio label="N"> 否 </el-radio>
                </el-radio-group>
              </td>
              <td>功能类别</td>
              <td style="width: 100%; padding-right: 0">
                <el-tree-select
                  style="width: 100%"
                  v-model="gndy.gnlb_dm"
                  :props="replaceFields"
                  :data="gnlbLists"
                  node-key="dm"
                  clearable
                  check-strictly
                  filterable
                  defaultExpandAll
                />
              </td>
            </tr>
            <tr>
              <td>
                <span>适用范围</span>
                <span class="red">*</span>
              </td>
              <td style="text-align: left">
                <el-checkbox-group v-model="gndy.syfw">
                  <el-checkbox v-for="option in plainOptions" :key="option" :label="option" />
                </el-checkbox-group>
              </td>
              <td>
                序号
                <span class="red">*</span>
              </td>
              <td>
                <input class="riginalInput" v-model="gndy.gnxh" />
              </td>
            </tr>
            <tr style="width: 100%">
              <td>
                是否菜单显示
                <span class="red">*</span>
              </td>
              <td style="text-align: left">
                <el-radio-group v-model="gndy.sfcdxs">
                  <el-radio label="Y"> 是 </el-radio>
                  <el-radio label="N"> 否 </el-radio>
                </el-radio-group>
              </td>
              <td style="width: 300px">说明</td>
              <td>
                <input class="riginalInput" v-model="gndy.bz" />
              </td>
            </tr>
          </table>
        </div>
      </div>
    </div>
    <!-- 添加分类 -->
    <div class="right" v-if="tjfLFlag">
      <div class="tab-box" style="padding: 10px">
        <div style="height: 50px; line-height: 50px">
          <div style="float: right">
            <el-button link type="primary" icon="DocumentAdd" @click="tjflBaoCun"> 保存 </el-button>
          </div>
        </div>
        <div style="height: 80px">
          <table class="riginalTable" style="table-layout: fixed" aria-describedby="分类">
            <tr>
              <th>上级分类</th>
              <th style="padding-right: 0">
                <el-tree-select
                  style="width: 100%"
                  v-model="tjflForm.fflbm"
                  :props="replaceFields"
                  :data="gnflLists"
                  node-key="bm"
                  clearable
                  check-strictly
                  :filter-node-method="filterFn"
                  filterable
                  defaultExpandAll
                />
              </th>
              <th>
                分类名称
                <span class="red">*</span>
              </th>
              <th>
                <input class="riginalInput" v-model="tjflForm.flmc" />
              </th>
            </tr>
            <tr>
              <td>
                序号
                <span class="red">*</span>
              </td>
              <td>
                <input class="riginalInput" v-model="tjflForm.flxh" />
              </td>
              <td>分类图标</td>
              <td>
                <input class="riginalInput" v-model="tjflForm.fltb" />
              </td>
            </tr>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.gnzj-permission {
  width: 100%;
  height: calc(100vh - 300px);
  background: #f0f2f5;
  display: flex;
  .gnzj-left {
    min-width: 280px;
    max-width: 280px;
    height: 100%;
    margin-right: 12px;
    background-color: #fff;
    border: 1px solid #dcdcdc;
    .tab-box {
      padding: 10px;
    }
    .el-tree {
      margin-top: 8px;
      &:deep(.el-tree-node) {
        &.is-current {
          position: relative;
          .el-tree-node__content {
            background-color: #d3effc;
            color: #409eff;
            &:hover {
              background-color: #d3effc;
            }
          }
        }
        & > .el-tree-node__children {
          & > .el-tree-node.is-current {
            & > .el-tree-node__content {
              background-color: #d3effc;
              color: #409eff;
              &:hover {
                background-color: #d3effc;
              }
            }
          }
          & > .el-tree-node:not(.is-current) {
            & > .el-tree-node__content {
              color: #666;
              background-color: #fff;
            }
          }
        }
        .el-tree-node__content {
          height: 32px;
          color: #666;
          &:hover {
            background-color: #dcdcdc;
          }
        }
      }
    }
  }
  .right {
    height: 100%;
    max-width: 908px;
    min-width: 908px;
    background-color: #fff;
    border: 1px solid #dcdcdc;
  }
}
</style>
